new Vue({
    el: '#app',
    data() {
        return {
            form: { PageNumber: 1, RowAmount: 20 },
            list: [],
            total: 0,
            pageAcquisition: null,
            // 单位映射与发货单位显示
            unitMap: {},
            shipUnitText: '单位',
            shipDeliveredTotal: 0,
            dialogReceiptVisible: false,
            receiptSaving: false,
            receiptContext: null,
            receiptForm: { amount: '' },
            receiptView: { contractAmount: '', stageDueAmount: '', actualAmount: '', voucherUrl: '', vouchers: [] },
            dialogShipVisible: false,
            shipSaving: false,
            shipContext: null,
            shipForm: { logisticsCode: '', logisticsNumber: '', deliveryQuantity: '', Picture_URL: '' },
            logisticsOptions: [],
            
        }
    },
    mounted() {
        this.getList();
    },
    methods: {
        handleBack() {
            window.location.href = '../acquisition_order/index.html';
        },
        async getList() {
            try {
                const params = new URLSearchParams(location.search);
                const orderSerial = params.get('orderSerial') || '';
                const cond = orderSerial ? `Acquisition_Order_SerialNumber='${orderSerial.replace(/'/g, "''")}'` : '';
                const res = await generalApi.generalQueryByTableName({ Data: 'acquisition_order', Condition: cond });
                const arr = Array.isArray(res) ? res : (res.Data || []);
                this.list = arr || [];
                this.total = (this.list || []).length;
                // 顶部原信息
                if (this.list && this.list[0] && this.list[0].Acquisition_Unit_Price_SerialNumber) {
                    const up = await generalApi.generalQueryByTableName({
                        Data: 'acquisition_unitprice',
                        Condition: `Acquisition_Unit_Price_SerialNumber='${String(this.list[0].Acquisition_Unit_Price_SerialNumber).replace(/'/g, "''")}'`
                    });
                    this.pageAcquisition = (Array.isArray(up) ? up[0] : (up && up.Data && up.Data[0])) || null;
                    // 加载单位映射
                    await this.loadUnitMap();
                    // 设置默认发货单位文本
                    try {
                        const serial = this.pageAcquisition && this.pageAcquisition.Article_Unit_SerialNumber;
                        const txt = this.getUnitText(serial);
                        this.shipUnitText = (txt && String(txt).trim()) || '';
                    } catch (e) {}
                }
                await this.bindStages();
                await this.loadLogisticsOptions();
            } catch (e) { console.error(e); }
        },
        async loadUnitMap() {
            try {
                const serials = [];
                if (this.pageAcquisition && this.pageAcquisition.Article_Unit_SerialNumber) {
                    serials.push(this.pageAcquisition.Article_Unit_SerialNumber);
                }
                const set = [...new Set(serials.filter(Boolean))];
                if (set.length === 0) { this.unitMap = {}; return; }
                const unitRes = await generalApi.generalQueryByTableName({
                    Data: 'article_unit',
                    Condition: `Article_Unit_SerialNumber IN (${set.map(u => `'${String(u).replace(/'/g, "''")}'`).join(',')})`
                });
                const unitArr = Array.isArray(unitRes) ? unitRes : (unitRes.Data || []);
                const map = {};
                (unitArr || []).forEach(u => { if (u.Article_Unit_SerialNumber) map[u.Article_Unit_SerialNumber] = u.Unit; });
                this.unitMap = map;
            } catch (e) { this.unitMap = {}; }
        },
        async bindStages() {
            const orders = this.list || [];
            const stageOrder = ['定金', '发货', '到货', '尾款'];
            for (const row of orders) {
                // 1) 读取订单阶段记录
                const cond = `Acquisition_Order_SerialNumber='${String(row.Acquisition_Order_SerialNumber||'').replace(/'/g, "''")}'`;
                const res = await generalApi.generalQueryByTableName({ Data: 'acquisition_order_paystages', Condition: cond });
                const stages = Array.isArray(res) ? res : (res.Data || []);

                // 2) 读取报价侧阶段方案：构建 name->percent 与 方案流水号->(name,percent) 映射
                const percentMap = {};
                const schemeMap = {};
                try {
                    const unitSerial = String(row.Acquisition_Unit_Price_SerialNumber || '').trim();
                    if (unitSerial) {
                        const spRes = await generalApi.generalQueryByTableName({
                            Data: 'acquisition_unitprice_staged_payment',
                            Condition: `Acquisition_Unit_Price_SerialNumber='${unitSerial.replace(/'/g, "''")}'`
                        });
                        const spArr = Array.isArray(spRes) ? spRes : (spRes && spRes.Data) || [];
                        (spArr || []).forEach(sp => {
                            const name = String(sp.Stage_Name || '').trim();
                            const schemeSerial = String(sp.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '').trim();
                            if (name) percentMap[name] = sp.Percent;
                            if (schemeSerial) schemeMap[schemeSerial] = { name, percent: sp.Percent };
                        });
                    }
                } catch (e) { /* ignore */ }

                // 3) 将阶段记录转字典
                const stageDict = {};
                for (const st of (stages || [])) {
                    const schemeSerial = String(st.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '').trim();
                    const fb = schemeSerial ? schemeMap[schemeSerial] : null;
                    const name = String(st.Stage_Name || (fb && fb.name) || '').trim();
                    if (!name) continue;
                    const percent = (fb && fb.percent !== undefined && fb.percent !== null && fb.percent !== '')
                        ? fb.percent
                        : (percentMap[name] !== undefined ? percentMap[name] : '');

                    // 金额优先展示：Due_Amount > Trading_Amount；若都缺失则为空
                    const dueRaw = (st.Due_Amount !== undefined && st.Due_Amount !== null && st.Due_Amount !== '')
                        ? Number(st.Due_Amount) : ((st.Trading_Amount !== undefined && st.Trading_Amount !== null && st.Trading_Amount !== '') ? Number(st.Trading_Amount) : '');
                    const collectedRaw = (st.Collection_Amount !== undefined && st.Collection_Amount !== null && st.Collection_Amount !== '')
                        ? Number(st.Collection_Amount) : 0;
                    const unRaw = (st.Unamount !== undefined && st.Unamount !== null && st.Unamount !== '')
                        ? Number(st.Unamount) : (dueRaw !== '' ? Number((dueRaw - collectedRaw).toFixed(2)) : 0);
                    stageDict[name] = {
                        serial: st.Acquisition_Order_Paystages_SerialNumber,
                        stage: name,
                        percent: (percent !== '' ? percent : (percentMap[name] !== undefined ? percentMap[name] : '')),
                        payWindow: this.formatPayWindow(st.Start_Datetime, st.End_Datetime),
                        receivableAmount: (dueRaw !== '' ? String(dueRaw) : ''),
                        collectedAmount: String(collectedRaw),
                        uncollectedAmount: String(unRaw),
                        // 按钮禁用状态
                        Pay_Status: st.Pay_Status,
                        Receipt_Pay_Status: st.Receipt_Pay_Status,
                        Ship_Status: st.Ship_Status,
                        Receipt_Ship_Status: st.Receipt_Ship_Status
                    };
                }

                // 4) 固定渲染四行：有数据填数据，无数据保持空框架，并根据百分比与订单金额回显
                const fixed = stageOrder.map(name => {
                    const s = stageDict[name] || {};
                    let fallbackReceivable = '';
                    let fallbackUncollected = 0;
                    try {
                        const p = Number((s.percent !== undefined && s.percent !== null && s.percent !== '') ? s.percent : (percentMap[name] || ''));
                        const amt = Number(row.Amount || 0);
                        if (Number.isFinite(p) && Number.isFinite(amt) && p > 0 && amt > 0) {
                            const calc = Number(((amt * p) / 100).toFixed(2));
                            fallbackReceivable = String(calc);
                            fallbackUncollected = calc;
                        }
                    } catch (e) { /* ignore */ }
                    return {
                        serial: s.serial || '',
                        stage: name,
                        percent: (s.percent !== undefined && s.percent !== null && s.percent !== '') ? s.percent : ((percentMap[name] !== undefined && percentMap[name] !== null && percentMap[name] !== '') ? percentMap[name] : ''),
                        payWindow: (s.payWindow !== undefined && s.payWindow !== null) ? s.payWindow : '',
                        receivableAmount: (s.receivableAmount !== undefined && s.receivableAmount !== null && s.receivableAmount !== '') ? s.receivableAmount : fallbackReceivable,
                        collectedAmount: (s.collectedAmount !== undefined && s.collectedAmount !== null) ? s.collectedAmount : 0,
                        uncollectedAmount: (s.uncollectedAmount !== undefined && s.uncollectedAmount !== null) ? s.uncollectedAmount : fallbackUncollected,
                        // 绑定按钮置灰状态（默认 0 常亮）
                        Pay_Status: (s.Pay_Status !== undefined && s.Pay_Status !== null && s.Pay_Status !== '') ? String(s.Pay_Status) : '0',
                        Receipt_Pay_Status: (s.Receipt_Pay_Status !== undefined && s.Receipt_Pay_Status !== null && s.Receipt_Pay_Status !== '') ? String(s.Receipt_Pay_Status) : '0',
                        Ship_Status: (s.Ship_Status !== undefined && s.Ship_Status !== null && s.Ship_Status !== '') ? String(s.Ship_Status) : '0',
                        Receipt_Ship_Status: (s.Receipt_Ship_Status !== undefined && s.Receipt_Ship_Status !== null && s.Receipt_Ship_Status !== '') ? String(s.Receipt_Ship_Status) : '0'
                    };
                });
                // 使用响应式赋值，确保阶段表格正确刷新
                if (typeof this.$set === 'function') {
                    this.$set(row, '_stagePaymentsFixed', fixed);
                } else {
                    row._stagePaymentsFixed = fixed;
                }
            }
        },
        formatPayWindow(start, end) {
            const s = start || ''; const e = end || '';
            return (s && e) ? `${s} ~ ${e}` : '';
        },
        contractStatusTagType(st) {
            const v = String(st||'');
            if (v==='11') return 'success';
            if (v==='10' || v==='01') return 'warning';
            return 'info';
        },
        formatContractStatus(st) {
            const v = String(st||'');
            if (v==='11') return '双方已确认';
            if (v==='10') return '买方已确认';
            if (v==='01') return '卖方已确认';
            return '双方未确认';
        },
        // 订单收付/发收汇总
        getOrderSummary(row) {
            const toNum = v => {
                if (v === null || v === undefined || v === '') return 0;
                const n = Number(v);
                return isNaN(n) ? 0 : n;
            };
            // 卖方视角
            return [
                {
                    label: '收款',
                    plan: toNum(row.Amount),
                    done: toNum(row.Collection_Amount),
                    remain: toNum(row.Unamount)
                },
                {
                    label: '发货',
                    plan: toNum(row.Quantity),
                    done: toNum(row.Delivery_Quantity),
                    remain: toNum(row.Undelivery_Quantity)
                }
            ];
        },
        // 根据单位流水号返回单位中文名
        getUnitText(serial) {
            const s = String(serial || '').trim();
            if (!s) return '';
            return this.unitMap[s] || s;
        },
        // 格式化地址（省市区+详细地址）
        formatAddress(s) {
            if (!s) return '';
            const p = s.ProvinceNumber || '';
            const c = s.CityNumber || '';
            const d = s.CountyNumber || '';
            const a = s.Detailed_Address || '';
            return `${p}${c}${d}${a}`;
        },
        // 操作可用性（最简版以避免模板报错）
        canOperate(row) { return !!row; },
        // 双方确认后才允许操作阶段按钮
        isContractConfirmed(row) { return String((row && row.Contract_Status) || '') === '11'; },
        actionEnabled(stageRow, type) {
            if (!stageRow) return false;
            const shipStatus = String(stageRow.Ship_Status || '');
            const receiptPayStatus = String(stageRow.Receipt_Pay_Status || '');
            // 收款：阶段已收满或未收为0则置灰
            if (type === 'receipt') {
                const uncollectedNum = Number(stageRow.uncollectedAmount || 0);
                if (receiptPayStatus === '1') return false;
                if (Number.isFinite(uncollectedNum) && uncollectedNum <= 0) return false;
                return true;
            }
            // 发货：阶段发货已完成则不可操作
            if (type === 'ship') {
                if (shipStatus === '1') return false;
                return true;
            }
            
            return !!stageRow;
        },
        // 收款弹窗
        openReceiptDialog(orderRow, stageRow) {
            this.receiptContext = { order: orderRow, stage: stageRow };
            this.receiptForm = { amount: '' };
            // 加载该阶段的付款凭证图片
            this.loadReceiptVouchers(stageRow);
            this.dialogReceiptVisible = true;
        },
        async loadReceiptVouchers(stageRow) {
            try {
                this.receiptView.vouchers = [];
                const stageSerial = String((stageRow && (stageRow.Acquisition_Order_Paystages_SerialNumber || stageRow.serial || '')) || '').trim();
                if (!stageSerial) return;
                // payment_detail：通过阶段号(Business_Order_SerialNumber)找到所有 Payment_SerialNumber
                const detRes = await generalApi.generalQueryByTableName({
                    Data: 'payment_detail',
                    Condition: `Business_Order_SerialNumber='${stageSerial.replace(/'/g, "''")}'`
                });
                const detArr = Array.isArray(detRes) ? detRes : (detRes && detRes.Data) || [];
                const serials = (detArr || []).map(d => d.Payment_SerialNumber).filter(Boolean);
                if (serials.length === 0) return;
                const uniq = [...new Set(serials.map(s => String(s)))];
                // payment_voucher：根据 Payment_SerialNumber 取凭证图片 Payment_Voucher_Picture
                const vouRes = await generalApi.generalQueryByTableName({
                    Data: 'payment_voucher',
                    Condition: `Payment_SerialNumber IN (${uniq.map(s => `'${s.replace(/'/g, "''")}'`).join(',')})`
                });
                const vouArr = Array.isArray(vouRes) ? vouRes : (vouRes && vouRes.Data) || [];
                const urls = (vouArr || []).map(v => v.Payment_Voucher_Picture).filter(Boolean).map(pic => {
                    return ((typeof imageApi !== 'undefined' ? imageApi : '') + String(pic));
                });
                this.receiptView.vouchers = urls;
                this.receiptView.voucherUrl = urls[0] || '';
            } catch (e) {
                console.error(e);
                this.receiptView.vouchers = [];
            }
        },
        async confirmReceipt() {
            try {
                if (!this.receiptContext || !this.receiptContext.order) { this.dialogReceiptVisible=false; return; }
                const order = this.receiptContext.order;
                const stage = this.receiptContext.stage || {};
                const now = getYMDHMSDate();
                const creator = $.cookie('user') || $.cookie('enterprise') || '';
                // 验证实际收款金额
                const inputAmount = String(this.receiptForm && this.receiptForm.amount || '').trim();
                if (!inputAmount) { this.$message.error('请输入实际收款金额'); return; }
                const amountNum = Number(inputAmount);
                if (!Number.isFinite(amountNum) || amountNum <= 0) { this.$message.error('请输入有效金额'); return; }

                const condSafeOrder = String(order.Acquisition_Order_SerialNumber || '').replace(/'/g, "''");
                const serialFromUI = String(stage.serial || '').trim();

                // 阶段行（原始行）
                let currentStageRow = null;
                if (serialFromUI) {
                    const stArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'acquisition_order_paystages',
                        Condition: `Acquisition_Order_Paystages_SerialNumber='${serialFromUI.replace(/'/g, "''")}'`
                    });
                    currentStageRow = Array.isArray(stArr) ? stArr[0] : (stArr && stArr.Data && stArr.Data[0]);
                } else {
                    const cond = `Acquisition_Order_SerialNumber='${condSafeOrder}' AND Stage_Name='${String(stage.stage||'').replace(/'/g,"''")}'`;
                    const stArr = await generalApi.generalQueryByTableNameWithOriginal({ Data: 'acquisition_order_paystages', Condition: cond });
                    currentStageRow = Array.isArray(stArr) ? stArr[0] : (stArr && stArr.Data && stArr.Data[0]);
                }
                const collectionOrderNumber = serialFromUI || (currentStageRow && currentStageRow.Acquisition_Order_Paystages_SerialNumber) || '';

                // 本阶段应收
                const collectionAmountRaw = (stage && stage.receivableAmount !== undefined && stage.receivableAmount !== null && stage.receivableAmount !== '')
                    ? stage.receivableAmount : (
                        (currentStageRow && (currentStageRow.Amount !== undefined)) ? currentStageRow.Amount : (
                            (currentStageRow && (currentStageRow.Trading_Amount !== undefined)) ? currentStageRow.Trading_Amount : (currentStageRow && currentStageRow.Due_Amount)
                        )
                    );
                const collectionAmountNum = Number(collectionAmountRaw || 0);

                // 累计已收款金额（查明细聚合）
                let oldCollected = 0;
                try {
                    if (collectionOrderNumber) {
                        const colArr = await generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'collection_detail',
                            Condition: `Collection_Order_Number='${String(collectionOrderNumber).replace(/'/g, "''")}'`
                        });
                        const list = Array.isArray(colArr) ? colArr : (colArr && colArr.Data) || [];
                        oldCollected = (list || []).reduce((sum, it) => {
                            const n = Number(it.Amount || 0);
                            return sum + (Number.isFinite(n) ? n : 0);
                        }, 0);
                    }
                } catch (e) { /* ignore */ }
                const newCollected = accAdd(oldCollected, amountNum);
                if (Number.isFinite(collectionAmountNum) && collectionAmountNum > 0 && newCollected > collectionAmountNum) {
                    this.$message.error('收款金额超出本阶段应收');
                    return;
                }
                const unAmountNum = Math.max(0, Number((collectionAmountNum - newCollected).toFixed(2)));
                const unAmountStr = String(unAmountNum);

                // 收款凭证
                const voucherPic = (currentStageRow && currentStageRow.Picture_URL) ? currentStageRow.Picture_URL : (this.receiptView && this.receiptView.voucherUrl) || '';

                // 构建提交数据：新增收款记录；其余更新写入 Modify（主表与阶段表）
                const dataset = { Add: { collection: this.getReceipt(condSafeOrder, String(collectionAmountNum || 0), collectionOrderNumber, inputAmount, voucherPic) }, Modify: {} };

                // 1) 累加主表收款并计算剩余未收：Unamount = Amount - Collection_Amount
                try {
                    const ordArr = await generalApi.generalQueryByTableNameWithOriginal({ Data: 'acquisition_order', Condition: `Acquisition_Order_SerialNumber='${condSafeOrder}'` });
                    const ordRow = Array.isArray(ordArr) ? ordArr[0] : (ordArr && ordArr.Data && ordArr.Data[0]);
                    if (ordRow) {
                        const oldOrderCol = Number(ordRow.Collection_Amount || 0);
                        const newOrderCol = accAdd(oldOrderCol, amountNum);
                        const orderAmt = Number(ordRow.Amount || 0);
                        const orderUn = Math.max(0, Number((orderAmt - newOrderCol).toFixed(2)));
                        ordRow.Collection_Amount = String(newOrderCol);
                        ordRow.Unamount = String(orderUn);
                        ordRow.Operation_ID = creator;
                        ordRow.Operation_Datetime = now;
                        dataset.Modify['acquisition_order'] = [ordRow];
                    }
                } catch (e) { /* ignore */ }

                // 2) 累加阶段收款并计算剩余未收：Unamount = Amount - Collection_Amount（若无 Amount，回退 Trading_Amount/Due_Amount）
                try {
                    if (currentStageRow) {
                        const oldStageCol = Number(currentStageRow.Collection_Amount || 0);
                        const newStageCol = accAdd(oldStageCol, amountNum);
                        const stageBaseAmt = Number(((currentStageRow.Amount !== undefined) ? currentStageRow.Amount : ((currentStageRow.Trading_Amount !== undefined) ? currentStageRow.Trading_Amount : currentStageRow.Due_Amount)) || 0);
                        const stageUn = Math.max(0, Number((stageBaseAmt - newStageCol).toFixed(2)));
                        currentStageRow.Collection_Amount = String(newStageCol);
                        currentStageRow.Unamount = String(stageUn);
                        currentStageRow.Operation_ID = creator;
                        currentStageRow.Operation_Datetime = now;
                        currentStageRow.Receipt_Pay_Status = (newCollected >= collectionAmountNum && collectionAmountNum > 0) ? '1' : '0';
                        dataset.Modify['acquisition_order_paystages'] = [currentStageRow];
                    }
                } catch (e) { /* ignore */ }

                // 3) 推进“下一阶段”的开始/结束时间（按流水号映射）
                try {
                    const orderSerial = String(order.Acquisition_Order_SerialNumber || '').trim();
                    const beginStr = now; // 当前时间作为下一阶段开始时间
                    const nowDate = new Date();

                    // 通过 SQLSerialNumber 获取阶段列表，定位当前阶段并取下一阶段的两个流水号
                    const sqlRows = await generalApi.generalQueryBySQLSerialNumber({
                        SQLSerialNumber: 'acquisition_payment_stages',
                        Condition: utf8ToBase64(orderSerial),
                        ExtensionCondition: ''
                    }).catch(() => []);
                    const rows = Array.isArray(sqlRows) ? sqlRows : [];
                    // 优先用阶段流水号匹配当前行，其次用中文阶段名
                    const curSerial = String((stage && (stage.serial || stage.Acquisition_Order_Paystages_SerialNumber || '')) || '').trim();
                    let idx = rows.findIndex(r => String(r.Acquisition_Order_Paystages_SerialNumber || '').trim() === curSerial);
                    if (idx < 0) idx = rows.findIndex(r => String(r.Stage_Name || '').trim() === String(stage.stage || '').trim());
                    if (idx < 0 && rows.length > 0) idx = 0; // ：默认从第一阶段推下一阶段
                    const nextLight = (idx >= 0 && idx + 1 < rows.length) ? rows[idx + 1] : null;
                    if (!nextLight) { /* 无下一阶段则跳过 */ } else {
                        const nextSerial = String(nextLight.Acquisition_Order_Paystages_SerialNumber || '').trim();
                        const quoteSerial = String(nextLight.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '').trim();

                        // 查下一阶段原始行（用于修改提交）
                        let nextStageRow = null;
                        if (nextSerial) {
                            const nextOrigRes = await generalApi.generalQueryByTableNameWithOriginal({
                                Data: 'acquisition_order_paystages',
                                Condition: `Acquisition_Order_Paystages_SerialNumber='${nextSerial.replace(/'/g, "''")}'`
                            });
                            const nextOrigArr = Array.isArray(nextOrigRes) ? nextOrigRes : (nextOrigRes && nextOrigRes.Data) || [];
                            nextStageRow = (nextOrigArr && nextOrigArr[0]) || null;
                        }

                        // 计算结束时间：开始时间 + 报价阶段 Pay_Time（天）
                        let endStr = '';
                        if (quoteSerial) {
                            const planRes = await generalApi.generalQueryByTableName({
                                Data: 'acquisition_unitprice_staged_payment',
                                Condition: `Acquisition_Unit_Price_Staged_Payment_SerialNumber='${quoteSerial.replace(/'/g, "''")}'`
                            });
                            const planArr = Array.isArray(planRes) ? planRes : (planRes && planRes.Data) || [];
                            const plan = planArr && planArr[0];
                            const payDays = Number((plan && plan.Pay_Time) || 0) || 0;
                            if (payDays > 0) {
                                endStr = getYMDHMSDate(new Date(nowDate.getTime() + payDays * 24 * 3600 * 1000));
                            }
                        }

                        if (nextStageRow) {
                            nextStageRow.Start_Datetime = beginStr;
                            if (endStr) nextStageRow.End_Datetime = endStr;
                            nextStageRow.Operation_ID = creator;
                            nextStageRow.Operation_Datetime = beginStr;
                            dataset.Modify['acquisition_order_paystages'] = (dataset.Modify['acquisition_order_paystages'] || []).concat([nextStageRow]);
                        }
                    }
                } catch (e) { /* ignore */ }

                // 提交
                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('已确认收款，下一阶段时间已更新');
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) { this.$message.error('收款确认失败'); }
            finally { this.dialogReceiptVisible = false; this.getList(); }
        },
        // 构造收款主表+子表（collection + collection_detail）嵌套结构
        getReceipt(Store_SerialNumber, Collection_Amount, Collection_Order_Number, Amount, Collection_Related_Number) {
            return [{
                Store_SerialNumber: Store_SerialNumber,
                Order_Type: '2',
                Collection_Date: getYMDHMSDate(),
                Collection_Amount: Collection_Amount,
                Enterprise_Info_SerialNumber: getCookie('enterprise'),
                Children: {
                    collection_detail: [{
                        Collection_Order_Number: Collection_Order_Number,
                        Collection_Type: '7',
                        Collection_Related_Number: Collection_Related_Number || '',
                        Amount: Amount,
                        Enterprise_Info_SerialNumber: getCookie('enterprise')
                    }]
                }
            }];
        },
        // 发货
        openShipDialog(orderRow, stageRow) {
            this.shipContext = { order: orderRow, stage: stageRow };
            this.shipForm = { logisticsCode: '', logisticsNumber: '', deliveryQuantity: '', Picture_URL: '' };
            try {
                const txt = this.getUnitText(this.pageAcquisition && this.pageAcquisition.Article_Unit_SerialNumber);
                this.shipUnitText = (txt && String(txt).trim()) || '单位';
            } catch (e) { this.shipUnitText = '单位'; }
            this.dialogShipVisible = true;
        },
        async loadLogisticsOptions() {
            try {
                const res = await generalApi.generalQueryByTableName({ Data: 'logistics_info', Condition: '' });
                const arr = Array.isArray(res) ? res : (res.Data || []);
                this.logisticsOptions = (arr || []).map(it => ({ Logistics_Code: it.Logistics_Code, Logistics_Name: it.Logistics_Name }));
            } catch (e) { this.logisticsOptions = []; }
        },
        async confirmShip() {
            if (!this.shipContext || !this.shipContext.order) return;
            // 基础校验
            const qty = Number(this.shipForm.deliveryQuantity || 0);
            if (!Number.isFinite(qty) || qty <= 0) { this.$message.error('请输入有效发货数量'); return; }
            const logisticsCode = String(this.shipForm.logisticsCode || '').trim();
            const logisticsNumber = String(this.shipForm.logisticsNumber || '').trim();
            if (!logisticsCode) { this.$message.error('请选择物流公司'); return; }
            if (!logisticsNumber) { this.$message.error('请输入物流单号'); return; }

            try {
                const orderSerial = String(this.shipContext.order.Acquisition_Order_SerialNumber || '').trim();
                if (!orderSerial) { this.$message.error('订单数据异常'); return; }

                // 查询订单主表，获取总数量与已发货数量
                const ordArr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'acquisition_order',
                    Condition: `Acquisition_Order_SerialNumber='${orderSerial.replace(/'/g, "''")}'`
                });
                const ordRow = Array.isArray(ordArr) ? ordArr[0] : (ordArr && ordArr.Data && ordArr.Data[0]);
                if (!ordRow) { this.$message.error('未找到订单'); return; }
                const orderQty = Number(ordRow.Quantity || 0) || 0;
                const shippedSoFar = Number(ordRow.Delivery_Quantity || 0) || 0;

                // 严格校验：本次发货不能超过剩余可发数量
                const remainBefore = Math.max(0, Number((orderQty - shippedSoFar).toFixed(2)));
                if (qty > remainBefore) { this.$message.error(`发货数量超出剩余可发(${remainBefore})`); return; }

                const newDelivery = Number((shippedSoFar + qty).toFixed(2));
                const newUndelivery = Math.max(0, Number((orderQty - newDelivery).toFixed(2)));
                ordRow.Delivery_Quantity = String(newDelivery);
                ordRow.Undelivery_Quantity = String(newUndelivery);

                // 构造保存数据集：
                const nowStr = getYMDHMSDate();
                const creator = getCookie('user') || getCookie('enterprise') || '';
                const dataset = { Add: { base_operation_log: [] }, Modify: { acquisition_order: [ordRow] } };

                // 写物流记录（采购-卖家）使用 acquisition_order_logistics，通过采购订单号关联
                dataset.Add['acquisition_order_logistics'] = [{
                    Acquisition_Order_Logistics_SerialNumber: '',
                    Acquisition_Order_SerialNumber: orderSerial,
                    Logistics_Code: logisticsCode,
                    Logistics_Number: logisticsNumber,
                    Delivery_Data: nowStr,
                    Delivery_Quantity: String(qty),
                    Enterprise_Info_SerialNumber: ordRow.Enterprise_Info_SerialNumber || '',
                    Creater_SerialNumber: creator,
                    Create_Datetime: nowStr,
                    Row_Status: '0',
                    Operation_ID: creator,
                    Operation_Datetime: nowStr,
                    Picture_URL: this.shipForm.Picture_URL || ''
                }];

                // 更新当前阶段发货状态（完成则置为1，未完成置为0）
                try {
                    const st = this.shipContext.stage || {};
                    const stageSerial = String(st.Acquisition_Order_Paystages_SerialNumber || '').trim();
                    let stageRec = null;
                    if (stageSerial) {
                        const sRes = await generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'acquisition_order_paystages',
                            Condition: `Acquisition_Order_Paystages_SerialNumber='${stageSerial.replace(/'/g, "''")}'`
                        });
                        const sArr = Array.isArray(sRes) ? sRes : (sRes && sRes.Data) || [];
                        stageRec = (sArr && sArr[0]) || null;
                    }
                    if (stageRec) {
                        const remainAfter = Math.max(0, Number((orderQty - newDelivery).toFixed(2)));
                        stageRec.Ship_Status = remainAfter <= 0 ? '1' : '0';
                        dataset.Modify['acquisition_order_paystages'] = [stageRec];
                    }
                } catch (e) { /* 阶段状态更新失败不阻断发货 */ }

                // 预写下一个阶段开始/结束时间
                try {
                    const now = new Date();
                    const beginStr = getYMDHMSDate(now);
                    const curStageName = String((this.shipContext && this.shipContext.stage && this.shipContext.stage.stage) || '').trim();
                    // 用 SQLSerialNumber 查询阶段列表，定位下一阶段行
                    const sqlRows = await generalApi.generalQueryBySQLSerialNumber({
                        SQLSerialNumber: 'acquisition_payment_stages',
                        Condition: utf8ToBase64(orderSerial),
                        ExtensionCondition: ''
                    }).catch(() => []);
                    const rows = Array.isArray(sqlRows) ? sqlRows : [];
                    let idx = rows.findIndex(r => String(r.Stage_Name || '').trim() === curStageName);
                    if (idx < 0 && rows.length > 0) idx = 0; // 容错：若找不到当前阶段，默认取第一条的下一阶段
                    const nextLight = (idx >= 0 && idx + 1 < rows.length) ? rows[idx + 1] : rows.find(r => String(r.Stage_Name || '').trim() === '到货');
                    if (!nextLight) { /* 无下一阶段则跳过 */ } else {
                        let nextStageRow = null;
                        const nextSerial = String(nextLight.Acquisition_Order_Paystages_SerialNumber || '').trim();
                        if (nextSerial) {
                            // 修改表必须查原值（Original）
                            const nextOrigRes = await generalApi.generalQueryByTableNameWithOriginal({
                                Data: 'acquisition_order_paystages',
                                Condition: `Acquisition_Order_Paystages_SerialNumber='${nextSerial.replace(/'/g, "''")}'`
                            });
                            const nextOrigArr = Array.isArray(nextOrigRes) ? nextOrigRes : (nextOrigRes && nextOrigRes.Data) || [];
                            nextStageRow = (nextOrigArr && nextOrigArr[0]) || null;
                        }

                        // 计算结束时间：开始时间 + 报价阶段 Pay_Time（天）
                        let payDays = 0;
                        const quoteSerial = String(nextLight.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '').trim();
                        if (quoteSerial) {
                            const planRes = await generalApi.generalQueryByTableName({
                                Data: 'acquisition_unitprice_staged_payment',
                                Condition: `Acquisition_Unit_Price_Staged_Payment_SerialNumber='${quoteSerial.replace(/'/g, "''")}'`
                            });
                            const planArr = Array.isArray(planRes) ? planRes : (planRes && planRes.Data) || [];
                            const plan = planArr && planArr[0];
                            payDays = Number((plan && plan.Pay_Time) || 0) || 0;
                        }
                        const endStr = payDays > 0 ? getYMDHMSDate(new Date(now.getTime() + payDays * 24 * 3600 * 1000)) : '';

                        if (nextStageRow) {
                            const needBegin = !nextStageRow.Start_Datetime || !String(nextStageRow.Start_Datetime).trim();
                            const needEnd = (!nextStageRow.End_Datetime || !String(nextStageRow.End_Datetime).trim()) && !!endStr;
                            if (needBegin || needEnd) {
                                if (needBegin) nextStageRow.Start_Datetime = beginStr;
                                if (needEnd) nextStageRow.End_Datetime = endStr;
                                dataset.Modify['acquisition_order_paystages'] = (dataset.Modify['acquisition_order_paystages'] || []).concat([nextStageRow]);
                            }
                        } else {
                            dataset.Add['acquisition_order_paystages'] = [{
                                Acquisition_Order_Paystages_SerialNumber: '',
                                Acquisition_Order_SerialNumber: orderSerial,
                                Stage_Name: String(nextLight.Stage_Name || '到货'),
                                Start_Datetime: beginStr,
                                End_Datetime: endStr,
                                Row_Status: '0'
                            }];
                        }
                    }
                } catch (e) { /* 阶段时间写入失败不阻断发货 */ }

                // 操作日志
                dataset.Add.base_operation_log.push({
                    Operation_Type: '0',
                    Operation_Path: getRelativePath(),
                    Operation_Description: '卖方确认发货',
                    Operation_Main: JSON.stringify({ Acquisition_Order_SerialNumber: orderSerial, Quantity: qty, Logistics_Code: logisticsCode, Logistics_Number: logisticsNumber }),
                    Operation_Interface: 'generalSaveByRequestBody',
                    Operation_IP: getIpAddress()
                });
console.log(dataset);//发货提交

                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('发货成功');
                    this.dialogShipVisible = false;
                    await this.getList();
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '发货失败';
                    this.$message.error(msg);
                }
            } catch (e) { console.error(e); this.$message.error('提交失败'); }
        },
        // 卖方确认：若买方已确认(10)则置为11，否则置为01，并补齐“定金”阶段时间
        async confirmByB(row) {
            if (!row || !row.Acquisition_Order_SerialNumber) return;
            try {
                const now = getYMDHMSDate();
                const creator = getCookie('user') || '';
                const current = String(row.Contract_Status || '00');
                const nextStatus = current === '10' ? '11' : '01';

                const orderArr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'acquisition_order',
                    Condition: `Acquisition_Order_SerialNumber='${String(row.Acquisition_Order_SerialNumber||'').replace(/'/g, "''")}'`
                });
                if (!Array.isArray(orderArr) || orderArr.length !== 1) throw new Error('未找到订单数据或存在重复记录');
                const od = { ...orderArr[0], Contract_Status: nextStatus, Operation_ID: creator, Operation_Datetime: now };
                const dataset = { Add: {}, Modify: { acquisition_order: [od] } };
                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (!(res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status==='success'))))) {
                    throw new Error((res && (res.Message || res.Error || res.msg)) || '保存失败');
                }
                row.Contract_Status = nextStatus;

                // 双方都确认：更新“第一阶段(定金)”开始/结束时间（避免中文条件查询，按流水号改写）
                if (nextStatus === '11') {
                    const orderSerial = row.Acquisition_Order_SerialNumber || '';
                    if (orderSerial) {
                        try {
                            // 从阶段列表获取第一阶段的两个流水号
                            const sqlRows = await generalApi.generalQueryBySQLSerialNumber({
                                SQLSerialNumber: 'acquisition_payment_stages',
                                Condition: utf8ToBase64(orderSerial),
                                ExtensionCondition: ''
                            }).catch(() => []);
                            const rows = Array.isArray(sqlRows) ? sqlRows : [];
                            // 优先按 Stage_Sort 升序选择第一条，其次按数组顺序
                            const first = rows.slice().sort((a,b)=> Number(a.Stage_Sort||0) - Number(b.Stage_Sort||0))[0] || rows[0];
                            if (first && (first.Acquisition_Order_Paystages_SerialNumber || first.Acquisition_Unit_Price_Staged_Payment_SerialNumber)) {
                                const paystageSerial = String(first.Acquisition_Order_Paystages_SerialNumber || '').trim();
                                const quoteStageSerial = String(first.Acquisition_Unit_Price_Staged_Payment_SerialNumber || '').trim();

                                // 查原值行（acquisition_order_paystages）
                                let stRow = null;
                                if (paystageSerial) {
                                    const stArr = await generalApi.generalQueryByTableNameWithOriginal({
                                        Data: 'acquisition_order_paystages',
                                        Condition: `Acquisition_Order_Paystages_SerialNumber='${paystageSerial.replace(/'/g, "''")}'`
                                    });
                                    stRow = Array.isArray(stArr) ? stArr[0] : (stArr && stArr.Data && stArr.Data[0]);
                                }

                                // 计算结束时间：从报价阶段取 Pay_Time
                                let endStr = '';
                                try {
                                    if (quoteStageSerial) {
                                        const planRes = await generalApi.generalQueryByTableName({
                                            Data: 'acquisition_unitprice_staged_payment',
                                            Condition: `Acquisition_Unit_Price_Staged_Payment_SerialNumber='${quoteStageSerial.replace(/'/g, "''")}'`
                                        });
                                        const planArr = Array.isArray(planRes) ? planRes : (planRes && planRes.Data) || [];
                                        const plan = planArr && planArr[0];
                                        const payDays = Number((plan && plan.Pay_Time) || 0) || 0;
                                        if (payDays > 0) {
                                            const calc = new Date(Date.now() + payDays * 24 * 3600 * 1000);
                                            endStr = getYMDHMSDate(calc);
                                        }
                                    }
                                } catch (e) {}

                                if (stRow) {
                                    stRow.Start_Datetime = now;
                                    if (endStr) stRow.End_Datetime = endStr;
                                    stRow.Operation_ID = creator;
                                    stRow.Operation_Datetime = now;
                                    await generalApi.generalSaveByRequestBody({ Data: { Modify: { acquisition_order_paystages: [stRow] } } });
                                }
                            }
                        } catch (e) { /* ignore staged time errors */ }
                    }
                    this.getList();
                }
                this.$message.success(nextStatus === '11' ? '买卖双方确认，合同生效' : '卖方已确认合同');
            } catch (e) {
                console.error(e);
                this.$message.error('卖方确认失败，请稍后重试');
            }
        },
        
        handlePageChange(p) { this.form.PageNumber = p; }
    }
});
